/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.namabank.servlet;

import com.namabank.helpdesk.model.CurrentUserModel;
import com.namabank.helpdesk.model.UserModel;
import com.namabank.util.ClientInfo;
import com.namabank.util.HttpUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.*;
import org.jsoup.parser.*;
import org.jsoup.select.Elements;
/**
 *
 * @author Gostep
 */
public class EvaluateParam {
    public static final String NOTICE_TAG_NAME = "notice";
    public static final String JAVASCRIPT_TAG_NAME = "javascript";
    public static final String JSON_TAG_NAME = "json";
    public static final String HTML_TAG_NAME = "div";

    public static final String ID_ATTR_NAME = "id";
    public static final String PARENTHREF_ATTR_NAME = "parentHref";

    private Calendar nowcalendar = null;
    private UserModel userModel = null;
    private CurrentUserModel currentUserModel = null;

    private Boolean commitWhenClose = true;
    private HttpServletRequest request = null;
    private Boolean isSendFile = false;
    private byte[] binaryData = null;
    private Calendar serverCalendar = Calendar.getInstance();
    private ClientInfo clientInfo;
    private Boolean developing = null;
    private Boolean fordebug = null;
    private JSONObject tag = new JSONObject();
    Element responseNode = new Element(Tag.valueOf("div"), "");
    //--------------------------------------------------------------------------

    public EvaluateParam() {
    }

    public EvaluateParam(HttpServletRequest request) {
        this.request = request;
        this.clientInfo = new ClientInfo(request.getHeader("User-Agent"), request.getRemoteAddr());
    }

    //--------------------------------------------------------------------------
    //<editor-fold defaultstate="collapsed" desc="Những hàm xử lý kết quả trả về">
    public void clearResponseText(){
        responseNode.empty();
    }
    public void clearResponseTextByTagName(String tagName){
        if(tagName != null && tagName.trim().length() > 0)
            responseNode.select(tagName).remove();
    }
    public void clearResponseTextByID(String id){
        if(id != null && id.length() > 0)
            responseNode.select("#" + id).remove();
    }
    public String getResponseString(){
        return responseNode.outerHtml();
    }
    @Override
    public String toString(){
        return getResponseString();
    }
    public void addResponseNode(Node node){
        if(node == null){
            return;
        }
        responseNode.appendChild(node);
    }
    public Element setResponseTextNode(String text, String tagName, String id, String parentHref){
        Element node = null;
        if(id != null && id.length() > 0){
            Elements eles = responseNode.select("#" + id);
            if(eles.size() > 0)
                node = eles.first();
            if(node != null && !node.tagName().equals(tagName)){
                node.remove();
                node = null;
            }
        }
        if(node == null){
            node = new Element(Tag.valueOf(tagName), "");
            if(id != null && id.length() > 0)
                node.attr(ID_ATTR_NAME, id);
            responseNode.appendChild(node);
        }
        if (parentHref == null)
            parentHref = "";
        node.attr(PARENTHREF_ATTR_NAME, parentHref);
        if(text == null) text = "";
        text = text.replace("-->", " -comment->");
        Comment comment = new Comment(text, "");
        node.appendChild(comment);
        return node;
    }
    public Element setResponseNotice(String text, String id, String parentHref){
        return setResponseTextNode(text, NOTICE_TAG_NAME, id, parentHref);
    }
    public Element setResponseJavascript(String text, String id, String parentHref){
        return setResponseTextNode(text, JAVASCRIPT_TAG_NAME, id, parentHref);
    }
    public Element setResponseJSON(JSONObject text, String id){
        return setResponseTextNode(text == null?"":text.toString(), JSON_TAG_NAME, id, null);
    }
    public Element setResponseJSON(String text, String id){
        return setResponseTextNode(text == null?"":text.toString(), JSON_TAG_NAME, id, null);
    }
    public Element setResponseHTML(String text, String id, String parentHref){

        return setResponseTextNode(text, HTML_TAG_NAME, id, parentHref);
    }
    //--------------------------------------------------------------------------
    public Element getResponseElementById(String id){
        Elements eles = responseNode.select("#" + id);
        if(eles.size() > 0)
            return eles.first();
        return null;
    }
    //--------------------------------------------------------------------------
    public Element setResponseError(String message){
        clearResponseText();
        return setResponseNotice(message, null, null).attr("stop_exec", "true");
    }
    public void setResponseRedirect(String message, String url){
        clearResponseText();
        setResponseNotice(message, null, null).attr("stop_exec", "true").attr("redirect", url);
    }
    public Element setResponseNotice(String message){
        clearResponseText();
        return setResponseNotice(message, null, null);
    }

    public Element constrainRole(Element ele){
        Elements lisRoleNeedHave = ele.select("[user_role]");
        if(userModel == null || userModel.getSmtbUserObj() == null){
            lisRoleNeedHave.remove();
            return ele;
        }
        for (int i = 0; i < lisRoleNeedHave.size(); i++) {
            Element curEle = lisRoleNeedHave.get(i);
            String needRole = curEle.attr("user_role");
            if (needRole == null || needRole.length() == 0) {
                continue;
            }
            String[] arrayNeed = needRole.split(",");
            int j = 0;
            for (; j < arrayNeed.length; j++) {
                arrayNeed[j] = arrayNeed[j].trim();
                if(arrayNeed[j].length() == 0)
                    continue;
                if (userModel.getListActiveRoleId().contains(arrayNeed[j].toUpperCase())) {
                    break;
                }
            }
            if (j == arrayNeed.length) {
                curEle.remove();
            }

        }
        return ele;
    }
    //--------------------------------------------------------------------------
    //</editor-fold>
    //--------------------------------------------------------------------------
    //<editor-fold defaultstate="collapsed" desc="Những hàm lưu lại thông tin biến evalparam">
    public JSONObject exportData() throws JSONException{
        JSONObject res = new JSONObject();
        res.put("user_id", getUserId());
        res.put("user_model", userModel);
        return res;
    }
    public boolean importData(JSONObject data){
        if(data == null) return false;
        if(!data.has("user_model"))
            return false;
        setUserModel((UserModel)data.get("user_model"));
        setCurrentUserModel((CurrentUserModel)data.get("current_user_model"));
        return true;
    }
    //</editor-fold>
    //--------------------------------------------------------------------------
    //<editor-fold defaultstate="collapsed" desc="Những hàm xử lý tham số request">
    /**
     * Lấy parameter từ HttpServletRequest, nếu nullIfEmpty = true sẽ trả về null
     * nếu parameter đó empty hoặc null
     * @param string tên parameter
     * @param nullIfEmpty nếu bằng true và parameter có giá trị rỗng thì trả về null
     * @return giá trị của parameter
     */
    public String getTrimmedParameter(String string, boolean nullIfEmpty) {
        String s = request.getParameter(string);
        if (s != null) {
            s = s.trim();
            if (s.isEmpty() && nullIfEmpty) {
                s = null;
            }
        }
        return s;
    }
    /**
     * Gọi hàm getTrimmedParameter với tham số nullIfEmpty = true;
     * @param string tên parameter
     * @return giá trị của parameter
     */
    public String getTrimmedNotEmptyParameter(String string) {
        return getTrimmedParameter(string, true);
    }
    /**
     * Gọi hàm request.getParameter(s);
     * @param string
     * @return giá trị của parameter
     */
    public String getRawParameter(String string) {
        return request.getParameter(string);
    }
    /**
     * Gọi hàm request.getContextPath()
     * @return địa chỉ tương đối của trang web
     */
    public String getContexPath() {
        return request.getContextPath();
    }
    public HashMap<String, Object> genParamsVariable(){
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("currentPage", HttpUtil.getFullHTTPPath(request,request.getServletPath()));
        params.put("sitePath", HttpUtil.getFullHTTPPath(request, ""));
        return params;
    }

    //</editor-fold>
    //--------------------------------------------------------------------------

    //--------------------------------------------------------------------------
    //<editor-fold defaultstate="collapsed" desc="Những hàm get/set">
    /**
     * @return the nowcalendar
     */
    public Calendar getNowcalendar() {
        return nowcalendar;
    }

    /**
     * @return the commitWhenClose
     */
    public Boolean getCommitWhenClose() {
        return commitWhenClose;
    }

    /**
     * @param commitWhenClose the commitWhenClose to set
     */
    public void setCommitWhenClose(Boolean commitWhenClose) {
        this.commitWhenClose = commitWhenClose;
    }

    /**
     * @return the request
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * @return the isSendFile
     */
    public Boolean getIsSendFile() {
        return isSendFile;
    }

    /**
     * @param isSendFile the isSendFile to set
     */
    public void setIsSendFile(Boolean isSendFile) {
        this.isSendFile = isSendFile;
    }

    /**
     * @return the binaryData
     */
    public byte[] getBinaryData() {
        return binaryData;
    }

    /**
     * @param binaryData the binaryData to set
     */
    public void setBinaryData(byte[] binaryData) {
        this.binaryData = binaryData;
    }

    /**
     * @return the clientInfo
     */
    public ClientInfo getClientInfo() {
        return clientInfo;
    }

    /**
     * @param clientInfo the clientInfo to set
     */
    public void setClientInfo(ClientInfo clientInfo) {
        this.clientInfo = clientInfo;
    }

    /**
     * @return the developing
     */
    public Boolean getDeveloping() {
        return developing;
    }

    /**
     * @param developing the developing to set
     */
    public void setDeveloping(Boolean developing) {
        this.developing = developing;
    }

    /**
     * @return the fordebug
     */
    public Boolean getFordebug() {
        return fordebug;
    }

    /**
     * @param fordebug the fordebug to set
     */
    public void setFordebug(Boolean fordebug) {
        this.fordebug = fordebug;
    }

    /**
     * @return the Tag
     */
    public JSONObject getTag() {
        return tag;
    }

    /**
     * @param Tag the Tag to set
     */
    public void setTag(JSONObject tag) {
        this.tag = tag;
    }

    /**
     * @return the userModel
     */
    public UserModel getUserModel() {
        return userModel;
    }

    /**
     * @param userModel the userModel to set
     */
    public void setUserModel(UserModel userModel) {
        this.userModel = userModel;
    }

    /**
     * @return the userId
     */
    public String getUserId() {
        if(this.userModel != null && this.userModel.getSmtbUserObj() != null)
            return this.userModel.getSmtbUserObj().getUSER_ID();
        return null;
    }

    /**
     * @return the serverCalendar
     */
    public Calendar getServerCalendar() {
        return serverCalendar;
    }

    /**
     * @param serverCalendar the serverCalendar to set
     */
    public void setServerCalendar(Calendar serverCalendar) {
        this.serverCalendar = serverCalendar;
    }

    public Date getServerDate(){
        if(this.serverCalendar != null)
            return this.serverCalendar.getTime();
        return null;
    }

    /**
     * @return the currentUserModel
     */
    public CurrentUserModel getCurrentUserModel() {
        return currentUserModel;
    }

    /**
     * @param currentUserModel the currentUserModel to set
     */
    public void setCurrentUserModel(CurrentUserModel currentUserModel) {
        this.currentUserModel = currentUserModel;
    }
    //</editor-fold>
}
